$(function() {

	/* SCROLL PAGINA */

	// Scroll verso l'elemento target
	$('#sidebar').scrollToFixed();
	$('.subNav a').click(function(e) {
		e.preventDefault();
		var item = e.target.href;
		var target = item.substr(item.indexOf("#"));
		$.scrollTo(target, 2500, { offset: -20, easing: 'easeOutExpo' });
	});

	
	/* SAVE SIM */

	// dialog
	$(function() {
		$('#X-save-dialog, #X-save-progress').dialog({
			autoOpen: false,
			modal: true,
			maxHeight: 800,
			maxWidth: 800,
		});
	});
	
	// trigger
	$('#X-sim-save').click(function() {
		$('[name="sim_name"]', $('#X-save-dialog')).val($('#sim_name').val()); // Legge sim_name da form
		var saveDialogButtons = {
			Salva: function() {
				$('[name="sim_name"]', $('#sim_form')).val($('[name="sim_name"]', $('#X-save-dialog')).val()); // Aggiorna sim_name nel form
				if (simulation_verify()) {
					simulation_save();
				}
				$(this).dialog('close');
			},
			Annulla: function() { $(this).dialog('close'); }
		};
		$('#X-save-dialog').dialog('option', 'buttons', saveDialogButtons);
		$('#X-save-dialog').dialog('open');
	});

	// salva con nome
	$('[name="sim_dup"]', $('#X-save-dialog')).change(function(e) {
		if ($(this).is(':checked')) { $('[name="sim_name"]', $('#X-save-dialog')).attr('disabled', false); simulation_save_as = true; }
		else { $('[name="sim_name"]', $('#X-save-dialog')).attr('disabled', true); simulation_save_as = false; }
		$.uniform.update('#sim_dup');
		
	});

	
	// Rilevamento modifiche
	/*
	$("#sim_form").change(function () {
		var section = $(".form-section:visible").attr('id');
		var menuitem = $("#mainNav a."+section);

		if (menuitem.hasClass('FLAG_MODIFIED')) {
			return;
		} else {
			menuitem.html(menuitem.html() + ' <span class="modified">(modificato)</span>');
			menuitem.addClass('FLAG_MODIFIED');
		}
	});
	*/

	/* NAVIGATION */

}); //* EOF $jquery.documentReady(/

var simulation_hash = null;
var simulation_save_as = false;

function simulation_verify() {
	var save_simulation_hash = $.md5($('input, textarea, select', $('#sim_form')).serialize());
	/* Nessuna modifica */ 
	if (simulation_hash === save_simulation_hash) {
		ModalDialog.info('Non sono state apportate modifiche');
		return false;
	}

	var data = { format: 'json', sim_hash: $.md5($('#sim_name').val()) };
	var sim_srvfail = sim_exists = run_exists = false;
	$.ajax({
		async: false,
		url: '/ajax/saveSimulation',
		data: $.param($.extend({ part: 'verify'}, data)),
		type: 'POST',
		dataType: 'json',
		error: function (jqXHR, textStatus, errorThrown) {
			sim_srvfail = true;
		},
		success: function(data) {
			if (typeof data.sim_exists !== "undefined" && data.sim_exists === true) {
				sim_exists = true; 
			}
			if (typeof data.run_exists !== "undefined" && data.run_exists === true) {
				run_exists = true; 
			}
		}
	});

	// Server fail
	if (sim_srvfail) {
		ModalDialog.alert('Errore durante la comunicazione con il database');
		return false;
	}
	
	// Nuova simulazione o simulazione esistente "salva con nome": verifica nome
	if ((simulation_hash === null || simulation_save_as) && sim_exists) {
		//alert("nuova sim");
		ModalDialog.alert('Esiste già una simulazione con questo nome');
		return false;
	}

	// Simulazione già eseguita: verifica run
	if (run_exists) {
		//alert("sim esist");
		ModalDialog.alert('Questa simulazione è già stata eseguita e non può essere modificata');
		return false;
	}

	return true;

	/*
	ModalDialog.open({
		type: 'warning',
		message: 'Esistono degli errori nel progetto'
	});
	return false;
	*/
}

function simulation_load() { }

function simulation_save() {
	var data = { format: 'json', sim_hash: $.md5($('#sim_name').val()), sim_save_as: simulation_save_as ? 1 : 0};

	$('#X-save-progress').dialog('open');
	/* Sim data */
	$.ajax({
		url: '/ajax/saveSimulation',
		data: $.param($.extend({ part: 'summary'}, data)) + '&' + $('input, textarea, select', $('[id^="liv_1"]')).serialize(),
		type: 'POST',
		dataType: 'json',
        async: false,
		error: function (jqXHR, textStatus, errorThrown) {
			$('#X-save-progress span').eq(0).removeClass().addClass('ui-icon ui-icon-alert');
		},
		success: function (data) {
			console.log(data);
			if (data === false) { this.error(); }
			else $('#X-save-progress span').eq(0).removeClass().addClass('ui-icon ui-icon-check');
		}
	});
	/* Site data */
	$.ajax({
		url: '/ajax/saveSimulation',
		data: $.param($.extend({ part: 'site'}, data)) + '&' + $('input, textarea, select', $('[id^="liv_2"]')).serialize(),
		type: 'POST',
		dataType: 'json',
		error: function (jqXHR, textStatus, errorThrown) {
			$('#X-save-progress span').eq(1).removeClass().addClass('ui-icon ui-icon-alert');
		},
		success: function (data) {
			console.log(data);
			if (data === false) { this.error(); }
			else $('#X-save-progress span').eq(1).removeClass().addClass('ui-icon ui-icon-check');
		}
	});
	/* Building data */
	$.ajax({
		url: '/ajax/saveSimulation',
		data: $.param($.extend({ part: 'building'}, data)) + '&' + $('input, textarea, select', $('[id^="liv_3"]')).serialize(),
		type: 'POST',
		dataType: 'json',
		error: function (jqXHR, textStatus, errorThrown) {
			$('#X-save-progress span').eq(2).removeClass().addClass('ui-icon ui-icon-alert');
		},
		success: function (data) {
			console.log(data);
			if (data === false) { this.error(); }
			else $('#X-save-progress span').eq(2).removeClass().addClass('ui-icon ui-icon-check');
		}
	});
	/* Zone data */
	$.ajax({
		url: '/ajax/saveSimulation',
		data: $.param($.extend({ part: 'zone'}, data)) + '&' + $('input, textarea, select', $('[id^="liv_4"]')).serialize(),
		type: 'POST',
		dataType: 'json',
		error: function (jqXHR, textStatus, errorThrown) {
			$('#X-save-progress span').eq(3).removeClass().addClass('ui-icon ui-icon-alert');
		},
		success: function (data) {
			console.log(data);
			if (data === false) { this.error(); }
			else $('#X-save-progress span').eq(3).removeClass().addClass('ui-icon ui-icon-check');
		}
	});
}